package top.javawa.token;

import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author aaron
 */
//@Configuration
@EnableJpaRepositories(
    basePackages = {"top.javawa.token.domain.second"},
    entityManagerFactoryRef = "entityManagerFactorySecond",
    transactionManagerRef = "transactionManagerSecond")
@EnableTransactionManagement
public class SecondDataSourceConfig {

  @Bean
  @ConfigurationProperties("spring.datasource.second")
  public DataSourceProperties secondDataSourceProperties() {
    return new DataSourceProperties();
  }

  @Bean
  @ConfigurationProperties("spring.datasource.secondary")
  public DataSource secondDataSource() {
    return secondDataSourceProperties().initializeDataSourceBuilder().build();
  }

  @Bean
  public PlatformTransactionManager transactionManagerSecond() {
    return new JpaTransactionManager(entityManagerFactorySecond().getObject());
  }

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactorySecond() {
    HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
    LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
    factoryBean.setDataSource(secondDataSource());
    factoryBean.setJpaVendorAdapter(jpaVendorAdapter);
    // 支持配置多个package
    factoryBean.setPackagesToScan("top.javawa.token.domain.second");
    factoryBean.setPersistenceUnitName("dbSecond");

    return factoryBean;
  }
}
